package com.example.administrator.kotiln.ui;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.example.administrator.kotiln.Path;
import com.example.administrator.kotiln.R;
import com.example.administrator.kotiln.adapter.MoreGoods_ListViewAdapter;
import com.example.administrator.kotiln.base.BaseActivity;
import com.example.administrator.kotiln.bean.MoreGoods_Data;
import com.example.administrator.kotiln.contants.Result;
import com.example.administrator.kotiln.utils.Json;
import com.example.administrator.kotiln.utils.Share;
import com.example.administrator.kotiln.utils.ToastUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/9/4.
 */

public class ListViewActivity extends BaseActivity {

    private MoreGoods_Data moreGoods_data;
    private PullToRefreshListView pullToRefreshListView;
    private int page = 1;
    private List<MoreGoods_Data.DataBean> dataList = new ArrayList<MoreGoods_Data.DataBean>();
    private List<MoreGoods_Data.DataBean> tempList = new ArrayList<MoreGoods_Data.DataBean>();
    private MoreGoods_ListViewAdapter listViewAdapter;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_listview);
        initView();
    }

    private void initView() {


        pullToRefreshListView = (PullToRefreshListView) findViewById(R.id.lv);
        getClassifyGoods();

        //设置模式 下拉：PULL_FROM_START,上拉：MANUAL_REFRESH_ONLY,上下:BOTH
        pullToRefreshListView.setMode(PullToRefreshBase.Mode.BOTH);

        pullToRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                page = 1;
                Share.d("走网络请求的方法" + page);
                getClassifyGoods();
                Share.d("走网络请求的方法");


            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                page++;
                Share.d("走网络请求的方法" + page);
                getClassifyGoods();
                Share.d("走网络请求的方法");

            }


        });


        ImageView back = (ImageView) findViewById(R.id.back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

    }


    /**
     * 分类的网络请求
     * Method:<br>
     * Description:<br>
     */
    private void getClassifyGoods() {

        String url = Path.CLASSIFY_GOODS_PATH;
        OkGo.<String>post(url)
                .tag(this)
                .cacheKey("moregoods")
                .cacheMode(CacheMode.DEFAULT)
                .retryCount(3)
                .params("page", page)
                .params("catid", 278)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Share.d("更多数据" + response.body());
                        Result result = Json.parse_message(response.body());
                        if (result.isState() && result != null) {
                            Gson gson = new Gson();
                            moreGoods_data = gson.fromJson(response.body(), new TypeToken<MoreGoods_Data>() {
                            }.getType());
                            handler.sendEmptyMessage(1);


                        } else {
                            ToastUtils.showToast(ListViewActivity.this, result.getMessage());
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        // handler.sendEmptyMessage(0);
                    }
                });


    }


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    break;
                case 1:
                    if (moreGoods_data.getData().size() > 0 && moreGoods_data.getData() != null) {
                        //判断是下拉刷新还是上拉加载
                        Share.d("page" + page);
                        if (!moreGoods_data.getMsg().equals("err")) {
                            //当有收获地址的时候，网络获取数据
                            tempList = moreGoods_data.getData();

                        } else
                            //当数据为空的时候，用空集合
                            tempList = new ArrayList<>();

                        if (page == 1) {
                            Share.d("page=1///" + page);//下拉刷新
                            //先清空数据，保证没有加载新数据
                            dataList.clear();
                            dataList.addAll(tempList);
                            listViewAdapter = new MoreGoods_ListViewAdapter(ListViewActivity.this, dataList);
                            pullToRefreshListView.setAdapter(listViewAdapter);

                            //结束刷新
                            pullToRefreshListView.onRefreshComplete();

                            //每次结束清空暂存集合
                            tempList.clear();


                        } else {
                            //先清空数据，保证没有加载新数据
                            dataList.clear();
                            dataList.addAll(tempList);
                            listViewAdapter.notifyDataSetChanged();

                            //结束刷新
                            pullToRefreshListView.onRefreshComplete();

                            //每次结束清空暂存集合
                            tempList.clear();


                        }
                    }
                    break;
                default:
                    break;
            }
        }
    };
}
